package main  
  
import (  
    "context"  
    "flag"  
    "fmt"  
    "path/filepath"  
    "time"  

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 
    corev1 "k8s.io/api/core/v1"
    "k8s.io/client-go/kubernetes"  
    "k8s.io/client-go/tools/clientcmd"  
    "k8s.io/client-go/util/homedir"  
)  
  
func main() {  
    var kubeconfig *string  
    if home := homedir.HomeDir(); home != "" {  
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")  
    } else {  
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")  
    }  
    flag.Parse()  
  
    // 使用kubeconfig文件构建config  
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)  
    if err != nil {  
        panic(err.Error())  
    }  
  
    // 创建clientset  
    clientset, err := kubernetes.NewForConfig(config)  
    if err != nil {  
        panic(err.Error())  
    }  
  
    // Watch Pods  
    watcher, err := clientset.CoreV1().Pods("").Watch(context.TODO(), metav1.ListOptions{})  
    if err != nil {  
        panic(err.Error())  
    }  
  
    fmt.Println("Watching pods...")  
    for {  
        select {  
        case event, ok := <-watcher.ResultChan():  
            if !ok {  
                fmt.Println("Watcher channel closed.")  
                return  
            }  
            fmt.Printf("Event type: %s\n", event.Type)  
            pod, ok := event.Object.(*corev1.Pod)  
            if !ok {  
                fmt.Println("Unexpected type:", event.Object)  
                continue  
            }  
            fmt.Printf("Pod name: %s, Namespace: %s, Status: %s\n", pod.Name, pod.Namespace, pod.Status.Phase)  
        case <-time.After(5 * time.Minute): // 可以在这里设置超时时间或继续条件  
            fmt.Println("Watch ended after 5 minutes.")  
            watcher.Stop()  
            return  
        }  
    }  
}
